﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Oragon.Architecture.Data.SqlBuilder
{
	/// <summary>
	/// Representa um Update Statement
	/// </summary>
	[Serializable]
	public class UpdateSQLBuilder : ISQLStatement, ICloneble<UpdateSQLBuilder>
	{
		public SqlLiteral TableName {get; set;}
		public List<SetItem> CollumnsAndValues { get; set; }
		public WhereClause WhereClause {get; set;}
		
		public UpdateSQLBuilder()
		{
			this.TableName = null;
			this.CollumnsAndValues = new List<SetItem>();
			this.WhereClause = new WhereClause();
		}


		public string ToSQL()
		{
			System.IO.StringWriter SQL = new System.IO.StringWriter(System.Globalization.CultureInfo.InvariantCulture);
			SQL.WriteLine("UPDATE {0} SET", this.TableName.Value);
			bool isFirst = true;
			foreach(SetItem insertItem in this.CollumnsAndValues)
			{
				if(isFirst==false)
					SQL.Write(",");
				SQL.WriteLine("{0} = {1}", insertItem.Column.Value, insertItem.Value.Value);
				
				isFirst = false;
			}
			SQL.Write(this.WhereClause.ToSQL());
			return SQL.ToString();
		}


		public UpdateSQLBuilder Clone()
		{
			System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			serializer.Serialize(stream, this);
			stream.Position = 0;
			UpdateSQLBuilder newInstance = (UpdateSQLBuilder)serializer.Deserialize(stream);
			stream.Close();
			return newInstance;
		}

	}
}
